#include <stdio.h>

#include <unistd.h>

#include <string.h>

#include <sys/types.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <netdb.h>

#include <stdlib.h>

#include <time.h>

#define PORT 1234

#define MAXDATASIZE 1000

void process(FILE *fp,int sockfd);

char *getMessage(char *sendline,int len,FILE *fp);

int main(int argc,char *argv[])

{

    int fd;

    struct hostent *he;

    struct sockaddr_in server;

    if(argc!=2)

    {

        printf("Usage: %s <IP Address>\n",argv[0]);

        exit(1);

    }

    if((he=gethostbyname(argv[1]))==NULL)

    {

        printf("gethostbyname error.\n");

        exit(1);

    }

    if((fd=socket(AF_INET,SOCK_STREAM,0))==-1)

    {

        perror("socket() error.\n");

        exit(1);

    }

    bzero(&server,sizeof(server));

    server.sin_family=AF_INET;

    server.sin_port=htons(PORT);

    server.sin_addr=*((struct in_addr *)he->h_addr);

    if(connect(fd,(struct sockaddr *)&server,sizeof(struct sockaddr))==-1)

    {

        perror("connect() error.\n");

        exit(1);

    }

    process(stdin,fd);

    close(fd);

    return 0;

}

void process(FILE *fp,int sockfd)

{

    char sendbuf[MAXDATASIZE];

    char recvbuf[MAXDATASIZE];

    int num;

    time_t t;

    t=time(NULL);

    printf("用户名：\n");

    if(fgets(sendbuf,MAXDATASIZE,fp)==NULL)

    {

        printf("lease enter your name,now you have exit.\n");

        return;

    }

    

    send(sockfd,sendbuf,strlen(sendbuf),0);

    while(getMessage(sendbuf,MAXDATASIZE,fp)!=NULL)

    {

        send(sockfd,sendbuf,strlen(sendbuf),0);

        if((num=recv(sockfd,recvbuf,MAXDATASIZE,0))==0)

        {

            printf("Server no send you any data.\n");

            return;

        }

        recvbuf[num]='\0';

        printf("服务器消息：%s\n",ctime(&t));

    }

    printf("Exit.\n");

}

char *getMessage(char *sendline,int len,FILE *fp)

{

    printf("请输入请求:\n");

    return(fgets(sendline,len,fp));

}
